package com.hengtiansoft.productcrawl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class ProductCrawl {
	private String queryURL = null;
	
	private String product = null;
	
	private String competitor = "";
	
	private String address = "95973";
	
	private String baseURL = "http://www.google.com/products";
	
	public ProductCrawl(String competitor) {
		this.competitor = competitor;
	}
	
	public ProductCrawl(String competitor, String address, String baseURL) {
		this.competitor = competitor;
		this.address = address;
		this.baseURL = baseURL;
	}
	
	public void setProduct(String product) throws UnsupportedEncodingException {
		this.product = product;
		String query;
		if (competitor.isEmpty()) {
			query = product;
		} else {
			query = product + " " + competitor;
		}
		this.queryURL = baseURL + "?" + "addr=" + address + "&q=" + URLEncoder.encode(query, "utf8");
	}
	
	public void setCompetitor(String competitor) {
		this.competitor = competitor;
	}
	
	public void setAddress(String address) {
		this.address = address;
	}
	
	public void setBaseURL(String baseURL) {
		this.baseURL = baseURL;
	}
	
	public String getQueryURL() throws UnsupportedEncodingException {
		return queryURL;
	}
	
	public String query() throws IOException {
		StringBuffer lines = new StringBuffer();
		URL url = new URL(queryURL);
		URLConnection con = url.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				con.getInputStream()));

		try {
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				lines.append(inputLine);
			}
		} finally {
			in.close();
		}
		return lines.toString();
	}
}

